package com.jml.springsecurity.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jml.springsecurity.core.properties.LoginType;
import com.jml.springsecurity.core.properties.SecurityProperties;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component("jmlAuthenticationSuccessHandler")//这是spring默认的一个成功处理器
public class JmlAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	//json的工具类
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private SecurityProperties securityProperties;
	//登录成功会被调用
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登录成功");

		String header = request.getHeader("Authorization");
		if (header != null && header.startsWith("Basic ")) {
			throw new UnapprovedClientAuthenticationException("请求头中没有client信息");
		}
		//抽取解码请求头中串
		String[] tokens = extractAndDecodeHeader(header, request);

		assert tokens.length == 2;

		String username = tokens[0];
		response.setContentType("application/json;charset=UTF-8");
		//authentication转为json写给前端
		response.getWriter().write(objectMapper.writeValueAsString(authentication));
	}


	private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
		byte[] base64Token = header.substring(6).getBytes("UTF-8");

		byte[] decoded;
		try {
			decoded = Base64.decode(base64Token);
		} catch (IllegalArgumentException var7) {
			throw new BadCredentialsException("Failed to decode basic authentication token");
		}

		String token = new String(decoded, "UTF-8");
		int delim = token.indexOf(":");
		if (delim == -1) {
			throw new BadCredentialsException("Invalid basic authentication token");
		} else {
			return new String[]{token.substring(0, delim), token.substring(delim + 1)};
		}
	}

}
